<script>
export default {
  name: "ChatStream",
  data() {
    return {
      info: "马云在哪个公司上班？",
      buffer: ""
    };
  },
  methods: {
  async send() {
                try {
                    // 清空之前的缓冲区
                    this.buffer = "";

                   // 发起流式请求
                   const response = await fetch(`http://localhost:8000/robot/?info=${encodeURIComponent(this.info)}`);

                    // 获取流式读取器
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder("utf-8");

                    while (true) {
                        // 读取数据
                        const { done, value } = await reader.read();
                        // 流式结束，跳出循环
                        if (done) break;
                        // 解码数据
                        let data = decoder.decode(value, { stream: true })
                        // 更新缓冲区
                        this.buffer += data;

                    }
                } catch (error) {
                    console.error("流式数据接收失败:", error);
                }
            },
  }
}
</script>

<template>
<div id="app">
    <h1 style="text-align: center;">流式数据接收示例</h1>

    <!-- 输入框和按钮 -->
    <el-row style="margin-bottom: 20px;">
        <el-col :span="16" :offset="4">
            <el-input
                v-model="info"
                placeholder="请输入内容"
                clearable
                style="width: 80%; margin-right: 10px;"
            ></el-input>
            <el-button type="primary" @click="send">搜索</el-button>
        </el-col>
    </el-row>

    <!-- 显示流式数据 -->
    <el-row>
        <el-col :span="16" :offset="4">
            <el-card shadow="always">
                <pre style="white-space: pre-wrap; word-wrap: break-word;">{{buffer}}</pre>
            </el-card>
        </el-col>
    </el-row>
</div>
</template>

<style scoped>

</style>
